package com.fyakm.daodejing.test001core;



import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class EvolutionController {
    private double crossoverRate;
    private double mutationRate;

    public EvolutionController(double crossoverRate, double mutationRate) {
        this.crossoverRate = crossoverRate;
        this.mutationRate = mutationRate;
    }

    // 执行遗传操作，这里简单示意一种结合两个亲本Java文件生成子代Java文件的方式（很简化，可优化）
    public Species performGeneticInheritance(Species parent1, Species parent2) throws IOException {
        String parent1FilePath = parent1.getJavaFilePath();
        String parent2FilePath = parent2.getJavaFilePath();

        // 读取亲本Java文件内容
        String parent1FileContent = new String(Files.readAllBytes(Paths.get(parent1FilePath)));
        String parent2FileContent = new String(Files.readAllBytes(Paths.get(parent2FilePath)));

        // 简单以一定概率决定采用哪个亲本的部分代码（类似基因交叉概念）
        String childFileContent = "";
        String[] parent1Lines = parent1FileContent.split("\n");
        String[] parent2Lines = parent2FileContent.split("\n");
        Random random = new Random();
        for (int i = 0; i < parent1Lines.length; i++) {
            if (random.nextDouble() < crossoverRate) {
                childFileContent += parent1Lines[i] + "\n";
            } else {
                childFileContent += parent2Lines[i] + "\n";
            }
        }

        // 创建临时文件来存储子代Java文件内容（实际应用可能需要更好的文件管理机制）
        File tempFile = File.createTempFile("child", ".java");
        Files.write(tempFile.toPath(), childFileContent.getBytes());

        // 假设输入数据和预期输出数据从亲本继承（可根据实际调整）
        List<String> inputDataList = new ArrayList<>(parent1.getInputDataList());
        List<String> expectedOutputList = new ArrayList<>(parent1.getExpectedOutputList());

        return new Species(tempFile.getAbsolutePath(), inputDataList, expectedOutputList);
    }

    // 执行变异操作，调用物种类自身的变异方法并传入变异概率
    public void performMutation(Species species) {
        species.mutate(mutationRate);
    }
}